/******************************************************************************
 *                                                                            *
 *               (c) 2008-2009 HutLab. All rights reserved.                   *
 *                        Eduardo Henrique Leite                              *
 *                                                                            *
 ******************************************************************************

 History:
 Created 02/01/2009

 */

package hutlab.sudoku.engine;

import hutlab.sudoku.engine.ai.*;
import hutlab.sudoku.engine.ui.*;
import hutlab.sudoku.engine.math.*;

/**
 * Sudoku Game Engine class.
 */
public class SudokuEngine {

    // ----- FIELDS -----

    private int mState;

    // ----- GETTERS -----

    /**
     * Returns the Game State.
     */
    public int getState(){
        return mState;
    }

    // ----- SETTERS -----

    /**
     * Sets the Game State.
     */
    public void setState(int state){
        mState = state;
    }

    // ----- CONSTRUCTOR -----

    /**
     * Creates a new SudokuEngine object.
     */
    public SudokuEngine(){
        this.mState = SudokuGameState.SUDOKU_MAINMENU;
    }

    // ----- PUBLIC -----

    public boolean getSolution(SudokuBoard board){
        SudokuPuzzle puzzle = getPuzzleFromBoard(board);
        SudokuBot bot = new SudokuBot(puzzle);
        if (bot.solve()){
            setBoardFromPuzzle(board, puzzle);
            return true;
        }
        else{
            return false;
        }
    }

    public int getSuggestion(SudokuBoard board){
        SudokuPuzzle puzzle = getPuzzleFromBoard(board);
        SudokuBot bot = new SudokuBot(puzzle);
        return bot.hint();
    }

    // ----- PRIVATE -----

    private SudokuPuzzle getPuzzleFromBoard(SudokuBoard board){
        SudokuPuzzle puzzle = new SudokuPuzzle();
        SudokuBoardCell cell;

        for (int i = 0; i< board.getCells().length; i++){
            cell = board.getCells()[i];
            if (cell.getGenerated()){
                puzzle.setValue(SudokuHelper.calculateRow(i, 9),
                        SudokuHelper.calculateColumn(i, 9), cell.getValue());
            }
        }
        return puzzle;
    }

    private void setBoardFromPuzzle(SudokuBoard board, SudokuPuzzle puzzle){
        SudokuBoardCell cell;

        for (int i=0;i<board.getCells().length;i++){
            cell = board.getCells()[i];
            if (!cell.getGenerated()){
                cell.setValue(puzzle.getPuzzle()[SudokuHelper.calculateRow(i, 9)]
                        [SudokuHelper.calculateColumn(i, 9)].getValue());
            }
        }
    }
}
